//
//  ST_AIRecommendSearchController.swift
//  btvideo
//
//  Created by mac on 2020/7/6.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit

class ST_AIRecommendSearchController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        view.addSubview(searchBtn)
        view.addSubview(cancel_btn)
        cancel_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
            make.height.equalTo(44)
            make.width.equalTo(58)
        }
        
        searchBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(38)
            make.centerY.equalTo(cancel_btn)
            make.right.equalTo(cancel_btn.snp.left).offset(-15)
        }
        
        
        
        
        view.addSubview(textField)
        textField.snp.makeConstraints { (make) in
            make.edges.equalTo(searchBtn).inset(UIEdgeInsets.init(top: 1, left: 33, bottom: 0, right: 16+11+3))
        }
        
        view.addSubview(delete_btn)
        delete_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(16)
            make.centerY.equalTo(searchBtn)
            make.right.equalTo(searchBtn).offset(-11)
        }
        
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(cancel_btn.snp.bottom)
        }
        
        textField.becomeFirstResponder()
        
        NotificationCenter.default.addObserver(self, selector: #selector(text_did_change_handle), name: UITextField.textDidChangeNotification, object: nil)
        
    }
    
//    MARK: - Properties
    fileprivate lazy var searchBtn:UIButton = {
        
        let control = ST_SearchButtonCreater.createSearchButton()
        return control
    }()
    
    fileprivate lazy var delete_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("search_bar_delte")!)
        control.addTarget(self, action: #selector(clear_input_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var cancel_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("取消")
        control.setTitleColorForAllStates(UIColor.init(hex: 0x333333)!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var textField:UITextField = {
       let control = UITextField()
        let attrString = NSMutableAttributedString(string: "请输入用户昵称")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.7, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.attributedPlaceholder = attrString
        control.textColor = UIColor.init(hex: 0x333333)
        control.tintColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.returnKeyType = .search
        control.enablesReturnKeyAutomatically = true
        control.delegate = self
        return control
    }()
    
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.contentInset = UIEdgeInsets.init(top: 10, left: 0, bottom: BTSafeAreaBottom + 30 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        
        control.register(cellWithClass: ST_AIRecommendSearchCell.self)
        
        
        control.separatorStyle = .none
        
        control.backgroundColor = UIColor.white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    
    fileprivate lazy var dadaArray:[String] = {
        
        if let array = UserDefaults.standard.stringArray(forKey: SC.home_search_history_list_key){
            return array
        }
        return [String]()
    }()
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    
}

extension ST_AIRecommendSearchController:UITextFieldDelegate{
    
    @objc fileprivate func clear_input_handle(){
        textField.text = nil
        self.text_did_change_handle()
    }
    
    @objc fileprivate func text_did_change_handle(){
        delete_btn.alpha = (textField.text?.isEmpty ?? true) ? 0 : 1
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        delete_btn.alpha = (textField.text?.isEmpty ?? true) ? 0 : 1
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        guard let str = textField.text,!str.isEmpty else {
            return true
        }
        
        self.textField.text = ""
        
        self.pushListController(searchStr: str)
        
        return true
    }
    
}

extension ST_AIRecommendSearchController{
    
    @objc fileprivate func close_handle(){
        
        self.goback_previous_controller(animated: false)
        
        
    }
    
    
    
}



extension ST_AIRecommendSearchController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 14+28
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.dadaArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withClass: ST_AIRecommendSearchCell.self, for: indexPath)
        
        cell.str = dadaArray[indexPath.row]
        
        cell.deleteClosure = {[weak self] iCell in
            
            if (self?.dadaArray.removeFirst(where: {$0 == iCell.str})) != nil{
                
                UserDefaults.standard.set(self?.dadaArray, forKey: SC.home_search_history_list_key)
                
                self?.tableView.reloadData()
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let str = dadaArray[indexPath.row]
        
        self.textField.text = ""
        
        
        self.pushListController(searchStr: str)
    }
    
    
    fileprivate func require_member_toast(){
        
        ST_MaidWayManager.shared.source = .搜索用户
        
        let vc  = ST_MemberSubscriberController.init(subscribeType: ST_BitianSubscribeType.精准搜人)

        vc.overCurrentContext = true

        GlobalPresent(toController: vc)
        
    }
    
    fileprivate func pushListController(searchStr:String){
        
        if FETCH_MEMBER_STATUS() != .subscribe && ST_BTUserInfoManager.shared.additional_attributes?.searchNeedVip == true{
            
            require_member_toast()
            
            return
        }
        
        
        let vc = ST_AIRecommendSearchedListController()
        
        vc.searchText = searchStr
        
        self.navigationController?.pushViewController(vc)
        
        var list = self.dadaArray
        
        if !list.contains(searchStr){
               
           list.insert(searchStr, at: 0)
           
           UserDefaults.standard.set(list, forKey: SC.home_search_history_list_key)
            
            self.dadaArray = list
            
            self.tableView.reloadData()
        }
        
    }
    
}




//MARK: - Cell
class ST_AIRecommendSearchCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        contentView.backgroundColor = UIColor.white
        
        contentView.addSubview(historyTextLabel)
        historyTextLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
        }
        
        contentView.addSubview(delete_btn)
        delete_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.right.equalToSuperview().offset(-15+(44-14)/2.0)
            make.centerY.equalToSuperview()
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var historyTextLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var delete_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("history_delete_icon")!)
        control.addTarget(self, action: #selector(deleteCurrHandle), for: UIControl.Event.touchUpInside)
        return control
    }()

    
    var str = ""{
        didSet{
            historyTextLabel.text = str
        }
    }
    
    var deleteClosure:((ST_AIRecommendSearchCell)->())?
    
}


extension ST_AIRecommendSearchCell{
    
    @objc fileprivate func deleteCurrHandle(){
        
        self.deleteClosure?(self)
        
    }
    
}
